<template>
  <div class="py-12">
    <div class="container mx-auto px-4">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex justify-center items-center py-20">
        <div
          class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"
        ></div>
      </div>

      <!-- 错误提示 -->
      <div v-else-if="error" class="text-center py-12">
        <i class="pi pi-exclamation-triangle text-5xl text-red-500 mb-4"></i>
        <h2 class="text-2xl font-semibold mb-2">加载失败</h2>
        <p class="text-gray-600 dark:text-gray-400 mb-6">
          {{ error }}
        </p>
        <router-link to="/blog" class="btn-primary"> 返回博客列表 </router-link>
      </div>

      <!-- 文章内容 -->
      <template v-else-if="post">
        <!-- 文章头部 -->
        <div class="max-w-4xl mx-auto mb-12">
          <div class="mb-6">
            <div class="flex flex-wrap gap-2 mb-4">
              <span
                v-for="tag in post.tags"
                :key="tag"
                class="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full text-sm font-medium"
              >
                {{ tag }}
              </span>
            </div>
            <h1 class="text-4xl font-bold mb-4 text-gray-800 dark:text-white">
              {{ post.title }}
            </h1>
            <div
              class="flex items-center text-gray-600 dark:text-gray-400 text-sm mb-6"
            >
              <span class="flex items-center">
                <i class="pi pi-calendar mr-1"></i>
                {{ formatDate(post.create_time) }}
              </span>
              <span class="mx-3">•</span>
              <span class="flex items-center">
                <i class="pi pi-clock mr-1"></i>
                {{ post.readTime }} 分钟阅读
              </span>
            </div>
          </div>

          <!-- 文章特色图片 -->
          <div
            v-if="post.image"
            class="mb-8 rounded-lg overflow-hidden shadow-lg h-[50vw]"
          >
            <img
              :src="baseUrl + post.image"
              :alt="post.title"
              class="w-full h-[50vw] object-cover"
            />
          </div>
        </div>

        <!-- 阅读进度条 -->
        <ReadingProgressBar />

        <!-- 文章内容 -->
        <div class="max-w-4xl mx-auto">
          <div class="prose prose-lg dark:prose-invert max-w-none mb-12">
            <!-- 这里使用v-html渲染文章内容，实际项目中应该使用安全的Markdown渲染库 -->
            <div v-html="formattedContent"></div>
          </div>
        </div>

        <!-- 文章底部 -->
        <div
          class="max-w-4xl mx-auto border-t border-gray-200 dark:border-gray-700 pt-8 mt-8"
        >
          <div
            class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4"
          >
            <div>
              <h3 class="text-lg font-semibold mb-2">分享这篇文章</h3>
              <div class="flex space-x-4">
                <a
                  href="#"
                  class="text-gray-600 dark:text-gray-400 hover:text-primary dark:hover:text-code-accent transition-colors duration-300"
                >
                  <i class="pi pi-twitter text-xl"></i>
                </a>
                <a
                  href="#"
                  class="text-gray-600 dark:text-gray-400 hover:text-primary dark:hover:text-code-accent transition-colors duration-300"
                >
                  <i class="pi pi-facebook text-xl"></i>
                </a>
                <a
                  href="#"
                  class="text-gray-600 dark:text-gray-400 hover:text-primary dark:hover:text-code-accent transition-colors duration-300"
                >
                  <i class="pi pi-linkedin text-xl"></i>
                </a>
                <a
                  href="#"
                  class="text-gray-600 dark:text-gray-400 hover:text-primary dark:hover:text-code-accent transition-colors duration-300"
                >
                  <i class="pi pi-copy text-xl"></i>
                </a>
              </div>
            </div>
            <div class="flex justify-between mt-8 mb-4 w-full">
              <router-link
                v-if="prevPostId && post.prevPost"
                :to="{ name: 'blog-detail', params: { id: prevPostId } }"
                class="btn-outline flex items-center transition-all duration-300 hover:bg-gray-100 dark:hover:bg-gray-800 max-w-[45%] p-3 rounded-lg border border-gray-200 dark:border-gray-700 w-[180px] overflow-hidden"
              >
                <div class="flex items-center overflow-hidden">
                  <i class="pi pi-arrow-left mr-2 flex-shrink-0"></i>
                  <div class="flex flex-col w-full overflow-hidden">
                    <span class="text-xs text-gray-500 dark:text-gray-400"
                      >上一篇</span
                    >
                    <span class="truncate font-medium w-full block">{{
                      post.prevPost.title
                    }}</span>
                  </div>
                </div>
              </router-link>
              <div v-else class="flex-grow-0"></div>
              <div class="flex-grow"></div>
              <router-link
                v-if="nextPostId && post.nextPost"
                :to="{ name: 'blog-detail', params: { id: nextPostId } }"
                class="btn-outline flex items-center transition-all duration-300 hover:bg-gray-100 dark:hover:bg-gray-800 max-w-[45%] p-3 rounded-lg border border-gray-200 dark:border-gray-700 w-[180px] overflow-hidden"
              >
                <div class="flex items-center overflow-hidden">
                  <div class="flex flex-col items-end w-full overflow-hidden">
                    <span class="text-xs text-gray-500 dark:text-gray-400"
                      >下一篇</span
                    >
                    <span
                      class="truncate font-medium w-full block text-right"
                      >{{ post.nextPost.title }}</span
                    >
                  </div>
                  <i class="pi pi-arrow-right ml-2 flex-shrink-0"></i>
                </div>
              </router-link>
              <div v-else class="flex-grow-0"></div>
            </div>
          </div>
        </div>

        <!-- 相关文章 -->
        <div v-if="relatedPosts.length > 0" class="max-w-4xl mx-auto mt-12">
          <h3 class="text-2xl font-bold mb-6">相关文章</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <BlogPostCard
              v-for="relatedPost in relatedPosts"
              :key="relatedPost.id"
              :post="relatedPost"
            />
          </div>
        </div>
      </template>

      <!-- 文章不存在 -->
      <div v-else class="text-center py-12">
        <i class="pi pi-exclamation-circle text-5xl text-gray-400 mb-4"></i>
        <h2 class="text-2xl font-semibold mb-2">文章不存在</h2>
        <p class="text-gray-600 dark:text-gray-400 mb-6">
          抱歉，您请求的文章不存在或已被删除。
        </p>
        <router-link to="/blog" class="btn-primary"> 返回博客列表 </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import {
  ref,
  computed,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  createApp,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import BlogPostCard from "../components/BlogPostCard.vue";
import ReadingProgressBar from "../components/ReadingProgressBar.vue";
import CodeCopyButton from "../components/CodeCopyButton.vue";
import { getBlogDetail, getBlogs } from "../api/index.ts";

export default {
  name: "BlogDetailView",
  components: {
    BlogPostCard,
    ReadingProgressBar,
    CodeCopyButton,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const post = ref(null);
    const isLoading = ref(false);
    const error = ref(null);
    const relatedPosts = ref([]);
    const prevPostId = ref(null);
    const nextPostId = ref(null);

    const fetchBlogDetail = async (id) => {
      isLoading.value = true;
      error.value = null;
      try {
        const response = await getBlogDetail(id);

        post.value = {
          ...response,
          readTime:
            response.readTime || Math.ceil(response.content.length / 1000), // 如果没有阅读时间，根据内容长度估算
        };

        // 获取相关文章和前后文章
        fetchRelatedPosts();
      } catch (err) {
        console.error("获取博客详情失败:", err);
        error.value = "获取文章详情失败，请稍后重试";
        post.value = null;
      } finally {
        isLoading.value = false;
      }
    };

    // 获取相关文章
    const fetchRelatedPosts = async () => {
      if (!post.value || !post.value.tags || post.value.tags.length === 0)
        return;

      try {
        // 使用第一个标签作为关键词搜索相关文章
        const params = {
          limit: 4,
          keywords: post.value.tags[0],
        };
        const response = await getBlogs(params);

        // 过滤掉当前文章，并最多取3篇作为相关文章
        relatedPosts.value = response.data
          .filter((p) => p.id != post.value.id)
          .slice(0, 3)
          .map((p) => ({
            ...p,
            readTime: p.readTime || Math.ceil((p.content?.length || 0) / 1000),
          }));

        // 使用后端返回的前后文章信息
        if (post.value.prevPost) {
          prevPostId.value = post.value.prevPost.id;
        } else {
          prevPostId.value = null;
        }

        if (post.value.nextPost) {
          nextPostId.value = post.value.nextPost.id;
        } else {
          nextPostId.value = null;
        }
      } catch (error) {
        console.error("获取相关文章失败:", error);
        relatedPosts.value = [];
      }
    };

    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return "";
      // 处理时间戳格式（秒级）
      const date = new Date(timestamp * 1000);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    };

    // 获取静态资源基础URL
    const baseUrl = import.meta.env.VITE_staticHost;

    // 格式化文章内容，高亮代码块
    const formattedContent = computed(() => {
      if (!post.value) return "";

      // 手动处理代码块，确保它们有正确的class属性
      let content = post.value.content;

      // 在nextTick中应用Prism高亮
      nextTick(() => {
        // 为代码块添加行号类
        document.querySelectorAll("pre").forEach((block) => {
          if (!block.classList.contains("line-numbers")) {
            block.classList.add("line-numbers");
          }
        });

        // 应用Prism高亮
        Prism.highlightAll();

        // 为代码块添加复制按钮
        document.querySelectorAll("pre code").forEach((block) => {
          // 检查是否已经有复制按钮
          const parentPre = block.parentNode;
          if (!parentPre.querySelector(".code-copy-button")) {
            const wrapper = document.createElement("div");
            wrapper.className = "relative";
            parentPre.parentNode.insertBefore(wrapper, parentPre);
            wrapper.appendChild(parentPre);

            // 创建复制按钮组件实例
            const app = createApp(CodeCopyButton, {
              code: block.textContent,
              isDark: document.documentElement.classList.contains("dark"),
            });

            const buttonEl = document.createElement("div");
            wrapper.appendChild(buttonEl);
            app.mount(buttonEl);
          }
        });
      });

      return content;
    });

    // ReadingProgressBar组件现在处理阅读进度

    // 监听路由参数变化，重新获取文章
    watch(
      () => route.params.id,
      (newId) => {
        if (newId) {
          fetchBlogDetail(newId);
        }
      },
      { immediate: true }
    );

    onMounted(() => {
      // 在组件挂载后应用代码高亮和行号
      nextTick(() => {
        // 为代码块添加行号类
        document.querySelectorAll("pre").forEach((block) => {
          if (!block.classList.contains("line-numbers")) {
            block.classList.add("line-numbers");
          }
        });

        // 应用Prism高亮
        Prism.highlightAll();
      });
    });

    onUnmounted(() => {
      // 清理工作已经在ReadingProgressBar组件中处理
    });

    return {
      post,
      formatDate,
      formattedContent,
      prevPostId,
      nextPostId,
      relatedPosts,
      isLoading,
      error,
      baseUrl,
    };
  },
};
</script>

<style>
pre[class*="language-"].line-numbers {
  padding-left: 3.8em !important; /* 增加左内边距，确保代码不会压着行号 */
  margin: 0.5em 0; /* 增加上下边距 */
}

/* 确保代码内容与行号有足够距离 */
code[class*="language-"] {
  margin-left: 1em !important; /* 增加代码内容左边距 */
  display: block;
}
/* 文章内容样式 */
.prose {
  @apply text-gray-800 dark:text-gray-200;
}

.prose h2 {
  @apply text-2xl font-bold mt-8 mb-4 text-gray-800 dark:text-white;
}

.prose h3 {
  @apply text-xl font-bold mt-6 mb-3 text-gray-800 dark:text-white;
}

.prose p {
  @apply mb-4 leading-relaxed;
}

.prose ul,
.prose ol {
  @apply mb-4 pl-5;
}

.prose li {
  @apply mb-2;
}

.prose pre {
  @apply my-6 rounded-lg overflow-x-auto max-w-full;
  /* 确保代码块可以横向滚动 */
  white-space: pre;
  word-wrap: normal;
  -webkit-overflow-scrolling: touch;
}

.prose code {
  @apply font-firacode text-sm;
}

.prose code:not(pre code) {
  @apply px-1 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-primary dark:text-code-accent;
}

/* 行号样式优化 */
.line-numbers .line-numbers-rows {
  @apply border-r border-gray-600 dark:border-gray-700;
  padding-right: 0.8em;
  left: 0;
  width: 3em !important; /* 增加行号区域宽度 */
}

.line-numbers {
  @apply relative; /* 设置相对定位 */
  counter-reset: linenumber;
  padding-left: 4.5em !important; /* 确保有足够空间容纳行号 */
}

/* 工具栏样式优化 */
div.code-toolbar > .toolbar {
  @apply opacity-0 transition-opacity duration-200;
  top: 0.3em;
  right: 0.3em;
}

div.code-toolbar:hover > .toolbar {
  @apply opacity-100;
}

div.code-toolbar > .toolbar > .toolbar-item > button {
  @apply bg-gray-700 dark:bg-gray-800 text-white px-2 py-1 rounded text-xs font-medium;
}

div.code-toolbar > .toolbar > .toolbar-item > button:hover {
  @apply bg-primary dark:bg-code-accent;
}

.prose blockquote {
  @apply pl-4 border-l-4 border-primary dark:border-code-accent italic my-6 text-gray-600 dark:text-gray-400;
}

.prose img {
  @apply rounded-lg my-6;
}

/* 阅读进度条 */
.reading-progress {
  @apply fixed top-0 left-0 h-1 z-50 bg-gradient-to-r from-primary to-code-accent transition-all duration-300 ease-out;
}
</style>
